package com.dc.base.viewmodel;

import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;

import com.dc.base.bean.LoadingDialogBean;

import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * @author 冰柠檬dc
 * ViewModel基类，管理rxJava发出的请求，ViewModel销毁同时也取消请求
 */
public class BaseViewModel extends ViewModel {

    private CompositeDisposable compositeDisposable;

    protected LoadingDialogLiveData loadingDialogLiveData = new LoadingDialogLiveData();

    protected MutableLiveData<Integer> failLiveData = new MutableLiveData<>();

    /**
     * 添加 rxJava 发出的请求
     */
    protected void addDisposable(Disposable disposable) {
        if (compositeDisposable == null || compositeDisposable.isDisposed()) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    public void getLoadingDialog(LifecycleOwner owner, Observer<LoadingDialogBean> observer) {
        loadingDialogLiveData.observe(owner, observer);
    }

    public MutableLiveData<Integer> getFailLiveData() {
        return failLiveData;
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
            compositeDisposable = null;
        }
        failLiveData = null;
        loadingDialogLiveData = null;
    }
}
